<?php
namespace verdor\message;
use verdor\REST;

/*
 * 发送短信验证码的具体步骤
 */
class Message
{
    private $accountSid;    //主帐号,对应开官网发者主账号下的 ACCOUNT SID
    private $accountToken;  //主帐号令牌,对应官网开发者主账号下的 AUTH TOKEN
    private $appId;         //应用Id，在官网应用列表中点击应用
    private $serverIP;      //请求地址    
    private $serverPort;    //请求端口，生产环境和沙盒环境一致
    private $softVersion;   //REST版本号，在官网文档REST介绍中获得。
    
    public function __construct()
    {
        $this->accountSid = $GLOBALS['config']['accountSid'];
        $this->accountToken = $GLOBALS['config']['accountToken'];
        $this->appId = $GLOBALS['config']['appId'];
        $this->serverIP = $GLOBALS['config']['serverIP'];
        $this->serverPort = $GLOBALS['config']['serverPort'];
        $this->softVersion = $GLOBALS['config']['softVersion'];
    }
    
    /**
     * 发送模板短信
     * @param to 手机号码集合,用英文逗号分开
     * @param datas 内容数据 格式为数组 例如：array('Marry','Alon')，如不需替换请填 null
     * @param $tempId 模板Id,测试应用和未上线应用使用测试模板请填写1，正式应用上线后填写已申请审核通过的模板ID
     */
    public function sendTemplateSMS($to,$datas,$tempId)
    {
        // 初始化REST SDK
        //global $accountSid,$accountToken,$appId,$serverIP,$serverPort,$softVersion;
        $rest = new REST($this->serverIP,$this->serverPort,$this->softVersion);
        $rest->setAccount($this->accountSid,$this->accountToken);
        $rest->setAppId($this->appId);
    
        // 发送模板短信
        echo "Sending TemplateSMS to $to <br/>";
        $result = $rest->sendTemplateSMS($to,$datas,$tempId);
        if($result == NULL ) {
            echo "result error!";
            //break;
        }
        if($result->statusCode!=0) {
            echo "error code :" . $result->statusCode . "<br>";
            echo "error msg :" . $result->statusMsg . "<br>";
            //TODO 添加错误处理逻辑
            return array(
                'status'        => 0,
                'error_code'    =>  $result->statusCode,
                'error_msg'     =>  $result->statusMsg
            );
        }else{
            echo "Sendind TemplateSMS success!<br/>";
            // 获取返回信息
            $smsmessage = $result->TemplateSMS;
            echo "dateCreated:".$smsmessage->dateCreated."<br/>";
            echo "smsMessageSid:".$smsmessage->smsMessageSid."<br/>";
            //TODO 添加成功处理逻辑
            return array(
                'status'    =>  1,
                'dateCreated'=>$smsmessage->dateCreated,
                'smsMessageSid'=>$smsmessage->smsMessageSid
            );
        }
    }
}